import os
import subprocess
import tkinter as tk
from tkinter import filedialog, messagebox


def install_library(library_name):
    try:
        __import__(library_name)
    except ImportError:
        subprocess.check_call(['pip', 'install', library_name])


def is_python_file(file_path):
    return file_path.endswith('.py')


def pack_python_file():
    file_path = file_entry.get()
    if not file_path:
        messagebox.showerror("错误", "请选择一个Python文件")
        return
    if not is_python_file(file_path):
        messagebox.showerror("错误", "选择的文件不是Python文件")
        return

    export_path = export_entry.get()
    if not export_path:
        export_path = os.getcwd()

    onefile_mode = onefile_var.get()
    windowed_mode = windowed_var.get()

    command = ['pyinstaller']
    if onefile_mode:
        command.append('--onefile')
    if windowed_mode:
        command.append('--windowed')
    command.append(file_path)
    command.append(f'--distpath={export_path}')

    try:
        subprocess.check_call(command)
        messagebox.showinfo("成功", "打包成功")
    except subprocess.CalledProcessError as e:
        messagebox.showerror("错误", f"打包失败: {str(e)}")


install_library('tkinter')
install_library('pyinstaller')

root = tk.Tk()
root.title("Python文件打包工具")

tk.Label(root, text="选择Python文件:").grid(row=0, column=0, padx=10, pady=10)
file_entry = tk.Entry(root, width=50)
file_entry.grid(row=0, column=1, padx=10, pady=10)


def browse_file():
    file_path = filedialog.askopenfilename(filetypes=[("Python files", "*.py")])
    file_entry.delete(0, tk.END)
    file_entry.insert(0, file_path)


tk.Button(root, text="浏览", command=browse_file).grid(row=0, column=2, padx=10, pady=10)

tk.Label(root, text="导出路径:").grid(row=1, column=0, padx=10, pady=10)
export_entry = tk.Entry(root, width=50)
export_entry.grid(row=1, column=1, padx=10, pady=10)


def browse_export_path():
    folder_path = filedialog.askdirectory()
    export_entry.delete(0, tk.END)
    export_entry.insert(0, folder_path)


tk.Button(root, text="浏览", command=browse_export_path).grid(row=1, column=2, padx=10, pady=10)

onefile_var = tk.BooleanVar()
tk.Checkbutton(root, text="打包为单个文件", variable=onefile_var).grid(row=2, column=0, padx=10, pady=10)

windowed_var = tk.BooleanVar()
tk.Checkbutton(root, text="无控制台窗口", variable=windowed_var).grid(row=2, column=1, padx=10, pady=10)

tk.Button(root, text="开始打包", command=pack_python_file).grid(row=3, columnspan=3, padx=10, pady=10)

root.mainloop()